import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
    baseURL: '/api', // url = base url + request url
    timeout: 60000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        if (sessionStorage.getItem('token') !== null) {
            config.headers[ 'token' ] = sessionStorage.getItem('token')
        }
        return config
    },
    (error) => {
        // do something with request error
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const res = response.data
        return res
    },
    (error) => {
        if (document.getElementsByClassName('el-message').length === 0) {
            Message({
                message: '服务不可用，请稍后再试',
                type: 'error',
                duration: 3 * 1000
            })
        }
        return Promise.reject(error)
    }
)

export default service
